<?php
namespace app\admin\controller;
use app\admin\model\Customers;
use app\admin\model\Users;
use app\admin\controller\AdminAuth;
use think\Validate;
use think\Image;
use think\Db;
use think\config;
use think\Request;
use app\admin\collection\permissionCollection;
use app\admin\collection\AliyunOss;
use app\admin\model\Group;

class CustomersController extends AdminAuth
{
	//模块基本信息
	private $data = array(
		'module_name' => '我的客户',
		'module_url'  => '/admin/Customers/',
		'module_slug' => 'Customers',
		'upload_path' => UPLOAD_PATH,
		'upload_url'  => '/public/uploads/',
    );
    //我的客戶列表
    public function index()
    {
        $where['D.user_id'] = Session('uid');  //当前登陆者
        input('mobile') ? $where['C.mobile'] = input('mobile') : false; //手机号
        input('c_nickname') ? $where['C.c_nickname'] = input('c_nickname') : false; //微信昵称
        input('customer_type') ? $where['C.customer_type'] = input('customer_type') : false; //客户状态
        if(input('startTime') && input('endTime')){
            $start = strtotime(input('startTime'));
            $end = strtotime(input('endTime'));
            $where['C.addtime'] = ['between',[$start, $end]];
        }

        $list = Db::name('distribution')
            ->alias('D')
            ->join('customers C','C.customers_id = D.customers_id')
            ->field('C.*')
            ->where($where)
            ->order('C.customers_id', 'DESC')
            ->paginate(10);

        $this->assign('data',$this->data);
        $this->assign('list',$list);
        return $this->fetch();
    }
    public function create()
    {
    	$this->data['edit_fields'] = array(
			'name' => array('type' => 'text', 'label'     => '客户姓名'),
			'c_nickname' => array('type' => 'text', 'label'     => '微信昵称'),
			'mobile' => array('type' => 'text', 'label'     => '手机号'),
            'sex'   => array('type' => 'radio', 'label' => '性别','default'=> array( 1 => '男', 2 => '女')),
            'customer_levlel'   => array('type' => 'radio', 'label' => '会员等级','default'=> array( 1 => '铜牌', 2 => '银牌',3 =>'金牌','4'=> '钻石')),
            'customer_type' => array('type' => 'radio', 'label'     => '客户状态','default'=> array( 1 => '新增', 2 => '潜在',3 =>'意向','4'=> '准客户','5'=> '合作客户','6'=> '已认证','7'=> '已放弃')),
            'remark' => array('type' => 'textarea', 'label'     => '备注'),

        );
        $admin_users = Db::name('users')->select();
        $this->assign('admin_users',$admin_users);
        $this->assign('data',$this->data);
        return view();
    }
    public function add()
    {
        //echo $_SESSION['think']['admin_nickname'];
        $customers = new Customers();
       // $data = input('post.');
        $data['name'] = input('name');
        $data['c_nickname'] = input('c_nickname');
        $data['mobile'] = input('mobile');
        $data['sex'] = input('sex');
        $data['customer_levlel'] = input('customer_levlel');
        $data['customer_type'] = input('customer_type');
        $data['remark'] = input('remark');
        $data['addtime'] = time();
        $user_id = Session('uid');  //当前登录用户id
        $rule = [
            //字段验证
			'name|用户名' => 'require',
			'mobile|手机号'   => 'length:11',
        ];
        // 数据验证
        $validate = new Validate($rule);
        $result   = $validate->check($data);
        if(!$result){
            return  $this->error($validate->getError());
        }
        if(true == Db::name('customers')->where(['mobile'=>input('mobile')])->find()){
            return $this->error('sorry!號碼已存在！','','','1');
        }
        if ($id = $customers->validate(true)->insertGetId($data)) {
            Db::name('distribution')->insert(['user_id'=>$user_id,'customers_id'=>$id,'addtime'=>time()]); //插入分配客户表

            return $this->success('客户添加成功',$this->data['module_url'],'','1');
        } else {
            return $this->error($customers->getError());
        }
    }
    /**
     * [read 读取用户数据]
     */
    public function read(Request $request)
    {
        $customers_id = input('customers_id');
        $admin_users = Db::name('users')->select();
        $this->assign('admin_users',$admin_users);
        //默认值设置
        $item = Db::name('customers')->where(['customers_id'=>$customers_id])->find();
        $art_id = Db::name('distribution')->where(['customers_id'=>$customers_id])->value('user_id');  //查询当前客户的所属用户
        $this->assign('art_id',$art_id);
        $this->assign('item',$item);
        $this->assign('data',$this->data);
        return view();
    }
    /**
     * [update 更新用户数据，read()提交表单数据到这里]
     */
    public function update($customers_id)
    {
        $customers = new Customers();
        //$data = input('post.');
        $data['name'] = input('name');
        $data['c_nickname'] = input('c_nickname');
        $data['mobile'] = input('mobile');
        $data['sex'] = input('sex');
        $data['customer_levlel'] = input('customer_levlel');
        $data['customer_type'] = input('customer_type');
        $data['remark'] = input('remark');
        $data['addtime'] = time();
        $rule = [
            //字段验证
			'name|用户名' => 'require',
			'mobile|手机号'   => 'length:11',
        ];
        // 数据验证
        $validate = new Validate($rule);
        $result   = $validate->check($data);
        if(!$result){
            return  $this->error($validate->getError());
        }
        if ($customers->validate(true)->where(['customers_id'=>$customers_id])->update($data)) {
            return $this->success('信息更改成功',$this->data['module_url'],'','1');
        } else {
            return $this->error($customers->getError());
        }
    }
    /**
     * [delete 删除用户数据(伪删除)]
     */
    public function delete($customers_id)
    {
        // 真.删除，不想用伪删除，请用这段
         $customer = Customers::get($customers_id);
         $data['customers_id'] = $customers_id;
         if ($customer) {
             Db::name('distribution')->where(['customers_id'=>$customers_id])->delete();  //删除分配表
             $customer->delete();  //删除客户表
             $data['error'] = 0;
         	$data['msg'] = '删除成功';
         } else {
         	$data['error'] = 1;
         	$data['msg'] = '删除失败';
         }
         return $data;
    }
    //新增跟进
    public function addfollow(){
        $data = input('post.');
        $data['follow_time'] = strtotime($data['follow_time']);
        $data['next_follow_time'] = strtotime($data['next_follow_time']);
        $result = Db::name('customers')->where(['customers_id'=>$data['customers_id']])->field('c_nickname,mobile')->find();
        $data['c_nickname'] = $result['c_nickname'];
        $data['mobile'] = $result['mobile'];
        $re = Db::name('follow_up')->insert($data);
        if($re){
            return $this->success('新增跟进成功',$this->data['module_url'],'','1');
        }else{
            return $this->error('新增跟进失败',$this->data['module_url'],'','1');
        }
    }
    //客户跟进记录
    public function followloglist(){
        $where['customers_id'] = input('customers_id');
        if(input('startTime') && input('endTime')){
            $start = strtotime(input('startTime'));
            $end = strtotime(input('endTime'));
            $where['follow_time'] = ['between',[$start, $end]];
            dump($where);exit;
        }
        $followloglist = Db::name('follow_up')->where($where)->order('follow_id desc')->paginate(10);
        $this->assign('followloglist',$followloglist);
        $this->assign('data',$this->data);
        return view();
    }
    //删除跟进log
    public function delfollow(){
        $follow_id = input('follow_id');
        $data['follow_id'] = input('follow_id');
        if ($follow_id) {
            $delfollow = Db::name('follow_up')->where(['follow_id'=>$follow_id])->delete();
            $data['error'] = 0;
            $data['msg'] = '删除成功';
        } else {
            $data['error'] = 1;
            $data['msg'] = '删除失败';
        }
        return $data;
    }
    //跟进记录详情
    public function followdetail(){
        $follow_id = input('follow_id');
        $re_follow = Db::name('follow_up')->where(['follow_id'=>$follow_id])->find();
        $re_follow['follow_time'] = date('Y-m-d H:i',$re_follow['follow_time']);
        $re_follow['next_follow_time'] = date('Y-m-d H:i',$re_follow['next_follow_time']);
        return json($re_follow);
    }
    //更新跟進记录记录
    public function updatefollowlog(){
        $data = input('post.');
        $data['follow_time'] = strtotime($data['follow_time']);
        $data['next_follow_time'] = strtotime($data['next_follow_time']);
        $re = Db::name('follow_up')->where(['follow_id'=>$data['follow_id']])->update($data);
        $customers_id = Db::name('follow_up')->where(['follow_id'=>$data['follow_id']])->value('customers_id');
        if($re){
            return $this->success('更新成功',$this->data['module_url'].'followloglist/customers_id/'.$customers_id,'','1');
        }else{
            return $this->error('更新上失败',$this->data['module_url'].'followloglist/customers_id/'.$customers_id,'','1');
        }
    }

    //他的拍品
    public function owngoods(){
        $mobile = input('mobile','111111111');
        $user_id = Db::connect('db_guwan')->name('users')
            ->where(['mobile'=>$mobile])->value('user_id');
        if($user_id == null){
            $this->error('号码不存在，线上无此用户!');
        }
        $owngoods = Db::connect('db_guwan')->name('goods')
            ->alias('G')
            ->join('users U','G.user_id = U.user_id')
            ->field('G.*,U.nickname,U.mobile,U.head_pic,U.user_level')
            ->where(['U.user_id'=>$user_id])
            ->select();
        if($owngoods == null){
            $this->error('该用户暂无拍品!');
        }
        foreach($owngoods as $k=>$v){
            $goods_id = $v['goods_id'];
            $owngoods[$k]['goods_images'] = Db::connect('db_guwan')->name('goods_images')
                ->field('image_url')
                ->where(['goods_id'=>$goods_id])
                ->select();
            foreach($owngoods[$k]['goods_images'] as $sk=>$sv){
                $res_id = $sv['image_url'];
                $owngoods[$k]['goods_images'][$sk]['image_url'] = (new AliyunOss(false))->getCurlofimg(Config::get('aliyun.bucket'), $res_id, 31536000);
            }
        }
        $this->assign('owngoods',$owngoods);

        return view();

    }
}